package ch.unifr.diva.multimodals.spherex;

import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Random;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

public class NetConfigurationActivity extends Activity {
	
	public static final int IP_ADDRESS=10;


	private static final String APPEND_TO_CONSOLE_INFO = "appendToConsoleInfo";
	
	
	private SeekBar gravity, friction, bounce;
	Button connect;

	Button disconnect;
	private TextView console, ipValue, portValue;
	ImageView connectionStatus;
	private ScrollView scrollView;
	PrintWriter output;
	OutputStream out;
	Socket socket;
	IpSetter s = new IpSetter();

	private String ip;

	private int port;


	private TestingThread t;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        ipValue = (TextView) findViewById(R.id.ipValue);
        portValue = (TextView) findViewById(R.id.portValue);
        
        
        connect = (Button) findViewById(R.id.connect);
        connect.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				connect.setEnabled(false);
				t = new TestingThread(NetConfigurationActivity.this);
				t.setRunning(true);
				t.start();
				}});
        disconnect = (Button) findViewById(R.id.disconnect);
        disconnect.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				t.setRunning(false);
				setEnabledConnection(false, true);
			}
        });
        connectionStatus = (ImageView) findViewById(R.id.connectionStatus);
        
        scrollView = (ScrollView) findViewById(R.id.consoleScrollView);
        console = (TextView) findViewById(R.id.consoleTextView);
        
        gravity = (SeekBar) findViewById(R.id.gravityBar);
        friction = (SeekBar) findViewById(R.id.frictionBar);
        bounce= (SeekBar) findViewById(R.id.bounceBar);
        
        
        gravity.setOnSeekBarChangeListener(new MyOnSeekBarChangeListener(getString(R.string.gravity), this));
        friction.setOnSeekBarChangeListener(new MyOnSeekBarChangeListener(getString(R.string.friction), this));
        bounce.setOnSeekBarChangeListener(new MyOnSeekBarChangeListener(getString(R.string.bounce), this));
 
        //Disabled connection when starting
        setEnabledConnection(false, false);
}
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_menu, menu);
        return true;
    }
    
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            confirmExit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.main_menu_ip_config:
            	Intent intent = new Intent(this, IpSetter.class);
                startActivityForResult(intent, IP_ADDRESS);
                return true;
                case R.id.main_menu_donate:
                	new AlertDialog.Builder(this).setMessage(R.string.donated).setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.cancel();
						}
					}).create().show();
                	return true;
                	case R.id.main_menu_quit:
                		confirmExit();
                		return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    
    @Override
    public void onBackPressed() {confirmExit();}  
    
    
private void confirmExit() {
	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage(R.string.confirm_quit)
           .setCancelable(false)
           .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                    System.exit(0);
               }
           })
           .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
               }
           }).setNeutralButton(R.string.maybe, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				final boolean quit=new Random(System.nanoTime()).nextInt(2)==1? true:false;
				AlertDialog.Builder builder = new AlertDialog.Builder(NetConfigurationActivity.this);
				builder.setMessage(getString(R.string.maybe_explanation)+"\n"+ getString(quit? R.string.maybe_decided_positive:R.string.maybe_decided_negative)+"\n").setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						if(quit)
							System.exit(0);
						else
							dialog.cancel();
					}
				});
				AlertDialog alert = builder.create();
				alert.show();
			}
		});
    AlertDialog alert = builder.create();
    alert.show();
	}

@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	super.onActivityResult(requestCode, resultCode, data);
	String text;
		switch(requestCode){
		case IP_ADDRESS:
			switch(resultCode){
			case RESULT_OK:
				this.ip = data.getStringExtra(IpSetter.NEW_IP);
				ipValue.setText(ip);
				this.port = data.getIntExtra(IpSetter.NEW_PORT, 0);
				portValue.setText(Integer.toString(port));
				text = getString(R.string.ipAddress_confirmOk)+" "+ip+":"+port;
				appendToConsole(text);
				Toast.makeText(NetConfigurationActivity.this, text, Toast.LENGTH_LONG).show();
				connect.setEnabled(true);
				break;
			case RESULT_CANCELED:
				text= getString(R.string.ipAddress_confirmCancel);
				appendToConsole(text);
				Toast.makeText(this,text, Toast.LENGTH_LONG).show();
				break;
			}
			break;
			default:
				break;
		}
		
	}

public void setEnabledConnection(boolean enabled, boolean enableConnectButton){
	connect.setEnabled(enableConnectButton);
	disconnect.setEnabled(enabled);
	connectionStatus.setImageDrawable((Drawable) getResources()
		.getDrawable(enabled? android.R.drawable.presence_online : android.R.drawable.presence_busy));
	gravity.setEnabled(enabled);
	friction.setEnabled(enabled);
	bounce.setEnabled(enabled);
}

public void sendNewValue(String id, int progress){
    try {
    	String msg = getString(R.string.progress_changed)+id+": "+progress;
    	//socket = new Socket(ip.getText().toString(), Integer.parseInt(port.getText().toString()));
		out = socket.getOutputStream();
	    output = new PrintWriter(out);
	    appendToConsole(msg);
		output.print(id+":"+progress);
	    output.flush();
	    out.flush();
	    //output.close();
	    //socket.close();
	} catch (Exception e) {
		setEnabledConnection(false, true);
	}
           

}

public void appendToConsole(final String text){
Log.d(APPEND_TO_CONSOLE_INFO, text);
console.setText(text+"\n"+console.getText());
//console.append(text+"\n");
//console.setText(text);
scrollView.fullScroll(ScrollView.FOCUS_DOWN);

}

public String getIp() {
	return ip;
}

public int getPort() {
	return port;
}

}

    
